package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.EsStockInventoryProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.EsStockInventoryMapper;
import com.ruoyi.system.domain.EsStockInventory;
import com.ruoyi.system.service.IEsStockInventoryService;

/**
 * 库存盘点单(es_stock_inventory)Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-07
 */
@Service
public class EsStockInventoryServiceImpl implements IEsStockInventoryService
{
    @Autowired
    private EsStockInventoryMapper esStockInventoryMapper;

    /**
     * 查询库存盘点单(es_stock_inventory)
     *
     * @param id 库存盘点单(es_stock_inventory)主键
     * @return 库存盘点单(es_stock_inventory)
     */
    @Override
    public EsStockInventory selectEsStockInventoryById(Long id) {
        EsStockInventory inventory = esStockInventoryMapper.selectEsStockInventoryById(id);
        if (inventory != null) {
            inventory.setProductList(esStockInventoryMapper.selectInventoryProductByInventoryId(id));
        }
        return inventory;
    }

    /**
     * 查询库存盘点单(es_stock_inventory)列表
     *
     * @param esStockInventory 库存盘点单(es_stock_inventory)
     * @return 库存盘点单(es_stock_inventory)
     */
    @Override
    public List<EsStockInventory> selectEsStockInventoryList(EsStockInventory esStockInventory)
    {
        return esStockInventoryMapper.selectEsStockInventoryList(esStockInventory);
    }

    /**
     * 新增库存盘点单(es_stock_inventory)
     *
     * @param esStockInventory 库存盘点单(es_stock_inventory)
     * @return 结果
     */
    @Override
    public int insertEsStockInventory(EsStockInventory esStockInventory) {
        esStockInventory.setCreateTime(DateUtils.getNowDate());
        esStockInventory.setStatus("未审核"); // 默认状态

        // 计算盘亏盘盈
        calculateProfitAndLoss(esStockInventory);

        int result = esStockInventoryMapper.insertEsStockInventory(esStockInventory);

        // 插入商品明细
        if (result > 0 && esStockInventory.getProductList() != null
                && !esStockInventory.getProductList().isEmpty()) {
            for (EsStockInventoryProduct product : esStockInventory.getProductList()) {
                product.setInventoryId(esStockInventory.getId());
                esStockInventoryMapper.insertInventoryProduct(product);
            }
        }
        return result;
    }

    @Override
    public int updateEsStockInventory(EsStockInventory esStockInventory) {
        // 计算盘亏盘盈
        calculateProfitAndLoss(esStockInventory);

        // 先删除原有商品明细
        esStockInventoryMapper.deleteInventoryProductByInventoryId(esStockInventory.getId());
        // 再插入新的商品明细
        if (esStockInventory.getProductList() != null
                && !esStockInventory.getProductList().isEmpty()) {
            for (EsStockInventoryProduct product : esStockInventory.getProductList()) {
                product.setInventoryId(esStockInventory.getId());
                esStockInventoryMapper.insertInventoryProduct(product);
            }
        }

        return esStockInventoryMapper.updateEsStockInventory(esStockInventory);
    }

    /**
     * 计算盘亏盘盈
     */
    private void calculateProfitAndLoss(EsStockInventory esStockInventory) {
        if (esStockInventory.getProductList() == null || esStockInventory.getProductList().isEmpty()) {
            esStockInventory.setProfitLossAmount(BigDecimal.ZERO);
            esStockInventory.setProfitCount(0);
            esStockInventory.setLossCount(0);
            return;
        }

        BigDecimal totalAmount = BigDecimal.ZERO;
        int profitCount = 0;
        int lossCount = 0;

        for (EsStockInventoryProduct product : esStockInventory.getProductList()) {
            // 计算差异数量
            int diff = product.getInventoryNum() - product.getStockNum();

            if (diff > 0) {
                // 盘盈
                product.setProfitLossType("profit");
                profitCount++;
            } else if (diff < 0) {
                // 盘亏
                product.setProfitLossType("loss");
                lossCount++;
            } else {
                // 无差异
                product.setProfitLossType(null);
            }

            // 计算盘亏盘盈金额
            if (diff != 0 && product.getUnitPrice() != null) {
                BigDecimal amount = product.getUnitPrice().multiply(new BigDecimal(Math.abs(diff)));
                product.setProfitLossAmount(amount);
                totalAmount = totalAmount.add(amount);
            } else {
                product.setProfitLossAmount(BigDecimal.ZERO);
            }
        }

        esStockInventory.setProfitLossAmount(totalAmount);
        esStockInventory.setProfitCount(profitCount);
        esStockInventory.setLossCount(lossCount);
    }



    /**
     * 批量删除库存盘点单(es_stock_inventory)
     *
     * @param ids 需要删除的库存盘点单(es_stock_inventory)主键
     * @return 结果
     */
    @Override
    public int deleteEsStockInventoryByIds(Long[] ids)
    {
        return esStockInventoryMapper.deleteEsStockInventoryByIds(ids);
    }

    /**
     * 删除库存盘点单(es_stock_inventory)信息
     *
     * @param id 库存盘点单(es_stock_inventory)主键
     * @return 结果
     */
    @Override
    public int deleteEsStockInventoryById(Long id)
    {
        return esStockInventoryMapper.deleteEsStockInventoryById(id);
    }

    @Override
    public int auditInventoryById(Long id) {
        // 查询库存盘点单
        EsStockInventory inventory = esStockInventoryMapper.selectEsStockInventoryById(id);
        if (inventory == null) {
            throw new ServiceException("库存盘点单不存在");
        }

        // 检查状态是否为"未审核"
        if (!"未审核".equals(inventory.getStatus())) {
            throw new ServiceException("只有状态为'未审核'的盘点单可以审核");
        }

        // 检查是否有盘亏盘盈记录
        if (inventory.getProfitLossAmount() != null && inventory.getProfitLossAmount().compareTo(BigDecimal.ZERO) != 0) {
            // 可以在这里添加额外的审核逻辑，比如超过一定金额需要特殊审批
        }

        // 更新状态为"审核通过"
        inventory.setStatus("审核通过");
        inventory.setAuditTime(DateUtils.getNowDate()); // 设置审核时间
        inventory.setAuditPersonId(SecurityUtils.getUserId()); // 设置审核人ID
        inventory.setAuditPersonName(SecurityUtils.getUsername()); // 设置审核人姓名

        return esStockInventoryMapper.updateEsStockInventory(inventory);
    }

}
